<template>
  <a-form-model ref="loginForm"
    :model="loginForm" :rules="rules"
    @submit="submitForm('loginForm')" @submit.native.prevent
    v-bind="layout"
  >
    <a-form-model-item has-feedback label="邮箱" prop="email">
      <a-input v-model="loginForm.email" ref="defaultFocus" />
    </a-form-model-item>
    <a-form-model-item has-feedback label="密码" prop="password">
      <a-input v-model="loginForm.password" type="password" autocomplete="off" />
    </a-form-model-item>
    <a-form-model-item :wrapper-col="{ span: 12, offset: 6 }">
      <a-button :loading="loading" type="primary" html-type="submit">
        Login
      </a-button>
      <a-button style="margin-left: 30px" type="link" @click="resetForm('loginForm')">
        Reset<a-icon style="font-size: 12px;" type="sync" />
      </a-button>
    </a-form-model-item>
  </a-form-model>
</template>

<script>
import { mapState } from 'vuex';

export default {
  computed: {
    ...mapState('userInfo', ['loading']),
  },
  data() {
    let checkPending;
    const mailReg = /^[\w-_]+@[\w.-_]+com$/;
    const checkUser = (rule, value, callback) => {
      clearTimeout(checkPending);
      if (!value) {
        return callback(new Error('请输入邮箱'));
      }
      checkPending = setTimeout(() => {
        if (mailReg.test(value)) callback();
        else callback(new Error('邮箱格式不正确'));
      }, 500);
      return null;
    };
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('请输入密码'));
      }
      return callback();
    };
    return {
      loginForm: {
        email: '',
        password: '',
      },
      rules: {
        email: [{ validator: checkUser, trigger: 'change' }],
        password: [{ validator: validatePass, trigger: 'change' }],
      },
      layout: {
        // span元素占多宽  offset左侧偏移量
        labelCol: { span: 4, offset: 2 },
        wrapperCol: { span: 12 },
      },
    };
  },
  mounted() {
    this.$refs.defaultFocus.$el.focus();
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const user = await this.$store.dispatch('loginInfo/login', this.loginForm);
          if (user) this.$router.push({ name: this.$route.query.target || 'home' });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
